package gui;

import javax.swing.JList;
import javax.swing.DefaultListModel;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * <p>
 * Title:MyList
 * </p>
 *
 * <p>
 * Description: List with listeners on mouse doubleclick and Enter key
 * </p>
 *
 * @author alexog
 * @version 1.0
 */
public class MyList extends JList {
    private ActionListener al = null;
    
    public MyList(DefaultListModel model) {
        super(model);
        
        addMouseListener(new MouseAdapter() {
            /**
             * mouseClicked
             *
             * @param me
             *            MouseEvent
             */
            public void mouseClicked(MouseEvent me) {
                if (al == null) {
                    return;
                }
                Object o[] = getSelectedValues();
                if (o.length > 1) {
                    return;
                }
                if (me.getClickCount() == 2) {
                    // Send command
                    al.actionPerformed(new ActionEvent(this,
                            ActionEvent.ACTION_PERFORMED, o[0].toString()));
                    me.consume();
                }
            }
        });
        
        addKeyListener(new KeyAdapter() {
            /**
             * keyReleased
             *
             * @param ke
             *            KeyEvent
             */
            public void keyReleased(KeyEvent ke) {
                if (al == null) {
                    return;
                }
                Object ob[] = getSelectedValues();
                if (ob.length > 1) {
                    return;
                }
                if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    al.actionPerformed(new ActionEvent(this,
                            ActionEvent.ACTION_PERFORMED, ob[0].toString()));
                    ke.consume();
                }
            }
        });
        this.setSelectedIndex(0);
    }
    
    public void addActionListener(ActionListener al) {
        this.al = al;
    }
}
